package com.qing.springcloud.config;


import com.qing.springcloud.handler.HttpRequestHandler;
import com.qing.springcloud.handler.WebSocketHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class WebSocketConfig extends ChannelInitializer<SocketChannel> {

    @Autowired
    private HttpRequestHandler httpRequestHandler;

    @Autowired
    private WebSocketHandler webSocketHandler;

    @Override
    protected void initChannel(SocketChannel ch) {
        ChannelPipeline pipeline = ch.pipeline();

        // HTTP编解码器
        pipeline.addLast(new HttpServerCodec());
        // 支持大数据流
        pipeline.addLast(new ChunkedWriteHandler());
        // HTTP聚合器
        pipeline.addLast(new HttpObjectAggregator(65536));
        // HTTP请求处理器
        pipeline.addLast(httpRequestHandler);
        // WebSocket协议处理器
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws", null, true));
        // 自定义WebSocket消息处理器
        pipeline.addLast(webSocketHandler);
    }
}
